<template>
  <div class="page-container">
    <div class="header">
      <el-icon class="back-btn" :size="20" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <h1>实名认证</h1>
    </div>
    <div class="content">
      <!-- 未认证状态 - 显示上传表单 -->
      <el-card v-if="realStatus === 0" class="verify-card">
        <template #header>
          <div class="card-header">
            <span>身份证认证</span>
          </div>
        </template>
        
        <div class="upload-section">
          <div class="upload-item">
            <div class="upload-label">请上传身份证正面</div>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="(res) => handleSuccess(res, 'front')"
              :before-upload="beforeUpload"
              :data="uploadData"
            >
              <img v-if="frontImageUrl" :src="frontImageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">点击上传身份证正面照片</div>
          </div>

          <div v-if="idCardInfo" class="info-section">
            <el-divider content-position="left">识别结果</el-divider>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="姓名">{{ idCardInfo.name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ idCardInfo.idNumber || '-' }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ idCardInfo.gender || '-' }}</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ idCardInfo.birthday || '-' }}</el-descriptions-item>
            </el-descriptions>
            
            <el-button type="primary" class="submit-btn" @click="handleSubmit">
              确认提交
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 已认证状态 - 显示认证成功信息 -->
      <el-card v-else-if="realStatus === 1" class="verify-card">
        <template #header>
          <div class="card-header">
            <span style="color: #67C23A;">✓ 实名认证成功</span>
          </div>
        </template>
        <div class="success-section">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ userInfo.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ maskIdCard(userInfo.idcard_number) || '-' }}</el-descriptions-item>
          </el-descriptions>
          <el-button type="primary" class="submit-btn" @click="goBack">
            返回
          </el-button>
        </div>
      </el-card>

      <!-- 待审核状态 - 显示审核提示 -->
      <el-card v-else-if="realStatus === 2" class="verify-card">
        <template #header>
          <div class="card-header">
            <span style="color: #E6A23C;">⏳ 审核中</span>
          </div>
        </template>
        <div class="pending-section">
          <div class="pending-message">{{ pendingMessage }}</div>
          <el-button type="primary" class="submit-btn" @click="goBack">
            返回
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { getQiniuToken, recognizeIdCard, submitVerify, checkIdcardAuth } from '@/api/verify'
import { wsManager } from '@/utils/websocket'

const router = useRouter()

const token = ref('')
const frontImageUrl = ref('')
const idCardInfo = ref(null)
const uploadData = ref({ token: '' })
const realStatus = ref(0) // 0: 未认证, 1: 已认证, 2: 待审核
const userId = ref(null)
const pendingMessage = ref('')
const userInfo = ref({})
let unsubscribeWs = null // WebSocket 取消监听函数

// 上传地址 - 七牛云华南区
const uploadUrl = 'https://up-z2.qiniup.com/'

// 掩码处理身份证号
const maskIdCard = (idcard) => {
  if (!idcard || idcard.length < 14) return idcard
  return idcard.substring(0, 6) + '********' + idcard.substring(14)
}

// 获取七牛云Token
const fetchToken = async () => {
  try {
    console.log('开始获取七牛云token...')
    const response = await getQiniuToken()
    console.log('token接口响应:', response)
    
    // 适配不同的返回格式
    if (response.data) {
      token.value = response.data
    } else if (response.token) {
      token.value = response.token
    } else {
      token.value = response
    }
    uploadData.value.token = token.value
    console.log('获取token成功:', token.value)
  } catch (error) {
    console.error('获取token失败详情:', error)
    console.error('错误响应:', error.response)
    
    if (error.response?.status === 401) {
      ElMessage.error('未登录或登录已过期，请重新登录')
    } else {
      ElMessage.error('获取上传凭证失败，请稍后重试')
    }
  }
}

// 上传前的校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  if (!token.value) {
    ElMessage.error('上传凭证未获取，请刷新页面重试')
    return false
  }
  
  return true
}

// WebSocket 消息处理
const handleWebSocketMessage = (data) => {
  console.log('[VerifyView] WebSocket 消息:', data)
  
  // 处理连接成功
  if (data.type === 'connected') {
    console.log('[VerifyView] WebSocket 已连接')
  }
  
  // 处理错误
  else if (data.type === 'error') {
    console.warn('[VerifyView] WebSocket 错误:', data.message)
  }
}

// 上传成功后的处理
const handleSuccess = async (res, side) => {
  console.log('==================== 上传成功 ====================')
  console.log('完整返回数据:', JSON.stringify(res, null, 2))
  console.log('res.key:', res.key)
  console.log('side:', side)
  
  // 图片URL - 优先使用七牛云返回的url，如果没有则手动拼接
  const imgUrl = res.url || `http://t4vs0af42.hn-bkt.clouddn.com/${res.key}`
  console.log('图片URL:', imgUrl)
  console.log('是否使用七牛云返回的url:', !!res.url)
  console.log('=================================================')
  
  if (side === 'front') {
    frontImageUrl.value = imgUrl
    ElMessage.success('正面上传成功，正在识别...')
    // 调用身份证正面识别接口
    await recognizeCard(imgUrl, 'front')
  }
}

// 调用百度云身份证识别API
const recognizeCard = async (imgUrl, side) => {
  try {
    console.log('开始识别身份证:', side, imgUrl, 'userId:', userId.value)
    // 调用后端接口，后端再调用百度云OCR
    const response = await recognizeIdCard(imgUrl, userId.value)
    console.log('OCR识别响应:', response)
    
    if (response.code === 200) {
      // 后端返回提示文本，更新状态为待审核
      pendingMessage.value = response.data || '您的实名认证正在审核中，请耐心等待1-3个工作日'
      realStatus.value = 2 // 更新为待审核状态
      ElMessage.success(response.data || '身份证识别成功！')
      console.log('审核提示:', response.data)
    } else {
      ElMessage.error('身份证识别失败: ' + (response.msg || response.data || '请重新上传'))
    }
  } catch (error) {
    console.error('识别失败详情:', error)
    ElMessage.error('身份证识别失败: ' + (error.message || '未知错误'))
  }
}

// 提交认证信息
const handleSubmit = async () => {
  if (!idCardInfo.value) {
    ElMessage.warning('请先上传身份证正面')
    return
  }
  
  if (!frontImageUrl.value) {
    ElMessage.warning('请上传身份证正面')
    return
  }
  
  if (!idCardInfo.value.name || !idCardInfo.value.idNumber) {
    ElMessage.warning('请确保已识别出姓名和身份证号')
    return
  }
  
  try {
    console.log('准备提交实名认证信息:', idCardInfo.value)
    
    // 调用提交实名认证的接口 - 匹配后端参数格式
    const response = await submitVerify({
      name: idCardInfo.value.name,
      idcard_number: idCardInfo.value.idNumber,
      gender: idCardInfo.value.gender || '',
      birth_date: idCardInfo.value.birthday || '',
      image_url: frontImageUrl.value
    })
    
    console.log('提交响应:', response)
    
    if (response.code === 1000) {
      ElMessage.success('实名认证提交成功！')
      // 延迟返回上一页
      setTimeout(() => {
        router.back()
      }, 1500)
    } else {
      ElMessage.error('提交失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(async () => {
  // 检查是否已登录
  const userToken = localStorage.getItem('token')
  if (!userToken) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  console.log('当前token:', userToken)
  
  // 获取用户ID
  const storedUserInfo = localStorage.getItem('userInfo')
  if (!storedUserInfo) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }
  const userInfoData = JSON.parse(storedUserInfo)
  userId.value = userInfoData.id
  
  if (!userId.value) {
    ElMessage.error('用户信息异常，请重新登录')
    return
  }
  
  // 初始化 WebSocket 连接
  console.log('[VerifyView] 初始化 WebSocket，userId:', userId.value)
  wsManager.init(userId.value)
  unsubscribeWs = wsManager.onMessage(handleWebSocketMessage)
  
  // 先检查是否已经实名认证
  try {
    console.log('查询认证状态，user_id:', userId.value)
    const response = await checkIdcardAuth(userId.value)
    console.log('进入认证页面前检查状态:', response)
    
    if (response.code === 200) {
      const data = response.data
      
      // 根据 is_real 状态判断显示的页面
      if (data.is_real === 1) {
        // 已认证 - 显示认证成功信息
        realStatus.value = 1
        userInfo.value = {
          name: data.name,
          idcard_number: data.idcard_number
        }
        console.log('用户已认证:', userInfo.value)
      } else if (data.is_real === 2) {
        // 待审核 - 显示审核提示
        realStatus.value = 2
        pendingMessage.value = data.message || '您的实名认证正在审核中，请耐心等待1-3个工作日'
        console.log('用户待审核，pendingMessage:', pendingMessage.value)
      } else if (data.is_real === 0) {
        // 未认证 - 显示上传表单
        realStatus.value = 0
        console.log('用户未认证，进入认证流程')
      }
    }
  } catch (error) {
    console.error('检查认证状态失败:', error)
    // 继续执行，允许用户进行认证
    realStatus.value = 0
  }
  
  // 未认证状态下获取七牛云token
  if (realStatus.value === 0) {
    fetchToken()
  }
})

// 组件卸载时断开 WebSocket
onUnmounted(() => {
  console.log('[VerifyView] 组件卸载，断开 WebSocket')
  if (unsubscribeWs) {
    unsubscribeWs()
  }
  // 不一定要断开连接，因为用户可能在其他页面也需要通知
  // wsManager.disconnect()
})
</script>

<style scoped>
.page-container {
  min-height: 100%;
  background-color: #f5f7fa;
}

.header {
  background: white;
  padding: 0 16px;
  height: 56px;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  gap: 12px;
}

.back-btn {
  cursor: pointer;
  color: #303133;
  transition: all 0.3s;
}

.back-btn:hover {
  color: #409eff;
}

.back-btn:active {
  transform: scale(0.9);
}

.header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.content {
  padding: 16px 16px 110px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.verify-card {
  width: 100%;
}

.card-header {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.upload-section {
  padding: 20px 0;
}

.upload-item {
  text-align: center;
  margin-bottom: 25px;
  width: 100%;
}

.upload-label {
  font-size: 15px;
  color: #606266;
  margin-bottom: 15px;
  font-weight: 500;
}

.avatar-uploader {
  display: inline-block;
}

:deep(.avatar-uploader .el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 200px;
  height: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 200px;
  height: 130px;
  display: block;
  object-fit: contain;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.info-section {
  margin-top: 30px;
  clear: both;
  width: 100%;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 44px;
  font-size: 16px;
}

.success-section {
  padding: 20px 0;
  text-align: center;
}

.pending-section {
  padding: 40px 20px;
  text-align: center;
}

.pending-message {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
  line-height: 1.6;
  padding: 20px;
  background-color: #FEF0F0;
  border-left: 4px solid #E6A23C;
  border-radius: 4px;
}
</style>

